package me.zhengjie.modules.customer.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.customer.domain.TCustomerContract;
import me.zhengjie.modules.customer.domain.TCustomerInfo;
import me.zhengjie.modules.customer.domain.TCustomerUser;
import me.zhengjie.modules.customer.repository.TCustomerInfoRepository;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.customer.repository.TCustomerUserRepository;
import me.zhengjie.modules.customer.service.TCustomerUserService;
import me.zhengjie.modules.customer.service.dto.TCustomerUserDTO;
import me.zhengjie.modules.customer.service.dto.TCustomerUserQueryCriteria;
import me.zhengjie.modules.customer.service.mapper.TCustomerUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author xuyukun
* @date 2019-07-21
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TCustomerUserServiceImpl implements TCustomerUserService {

    @Autowired
    private TCustomerInfoRepository tCustomerInfoRepository;

    @Autowired
    private TCustomerUserRepository tCustomerUserRepository;

    @Autowired
    private TCustomerUserMapper tCustomerUserMapper;

    @Override
    public Object queryAll(TCustomerUserQueryCriteria criteria, Pageable pageable){
        Page<TCustomerUser> page = tCustomerUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tCustomerUserMapper::toDto));
    }

    @Override
    public Object queryAll(TCustomerUserQueryCriteria criteria){
        return tCustomerUserMapper.toDto(tCustomerUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TCustomerUserDTO findById(Long id) {
        Optional<TCustomerUser> tCustomerUser = tCustomerUserRepository.findById(id);
        ValidationUtil.isNull(tCustomerUser,"TCustomerUser","id",id);
        return tCustomerUserMapper.toDto(tCustomerUser.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TCustomerUserDTO create(TCustomerUser resources) {
        if(tCustomerUserRepository.findByAccount(resources.getAccount())!=null){
            throw new BadRequestException("客户账号重复，请重新输入");
        }
        operateObject(resources);
        return tCustomerUserMapper.toDto(tCustomerUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TCustomerUser resources) {

        Optional<TCustomerUser> optionalTCustomerUser = tCustomerUserRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTCustomerUser,"TCustomerUser","id",resources.getId());

        TCustomerUser tCustomerUser = optionalTCustomerUser.get();
        if(!resources.getAccount().equals(tCustomerUser.getAccount())){
            if(tCustomerUserRepository.findByAccount(resources.getAccount())!=null){
                throw new BadRequestException("客户账号重复，请重新输入");
            }
        }
        // 此处需自己修改
        resources.setId(tCustomerUser.getId());
        operateObject(resources);
        tCustomerUserRepository.save(resources);
    }

    private void operateObject(TCustomerUser resources) {
        Timestamp date = new Timestamp(System.currentTimeMillis());
        resources.setCreatTime(date);
        TCustomerInfo optionalTCustomerInfo = tCustomerInfoRepository.findById(Long.valueOf(resources.getCustomerId())).get();
        if (optionalTCustomerInfo != null) {
            resources.setCustomerName(optionalTCustomerInfo.getCustomerName());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        tCustomerUserRepository.deleteById(id);
    }

    @Override
    public TCustomerUserDTO findByUsername(String userName) {
        TCustomerUser user = null ;
        user = tCustomerUserRepository.findByUsername(userName) ;
        if (user == null) {
            throw new EntityNotFoundException(TCustomerUser.class, "username", userName);
        } else {
            return tCustomerUserMapper.toDto(user);
        }
    }

    @Override
    public TCustomerUserDTO findByAccount(String account) {
        TCustomerUser user = null ;
        user = tCustomerUserRepository.findByAccount(account) ;
        if (user == null) {
            throw new EntityNotFoundException(TCustomerUser.class, "account", account);
        } else {
            return tCustomerUserMapper.toDto(user);
        }
    }
}